from django.core.cache import cache

from rest_framework.authentication import BaseAuthentication
from utils.errors import LoginError
from user.models import User


class UserLoginAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.query_params.get('token') if request.query_params else request.data.get('token')
        if not token:
            raise LoginError()
        user_id = cache.get(token)
        if not user_id:
            raise LoginError()
        user = User.objects.get(pk=user_id)
        return user, token
